﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace unTroublemaker
{
    public class SpecificationTester
    {
        private readonly Specification _specification;

        public SpecificationTester(Specification specification)
        {
            _specification = specification;
            ListenToItems(_specification.Items);
        }

        private void ListenToItems(IEnumerable<ISpecificationItem> items)
        {
            foreach (var item in items)
            {
                item.StatusChanged += OnItemStatusChanged;
                ListenToItems(item.ChildItems);
            }
        }

        private void OnItemStatusChanged(ISpecificationItem sender, StatusChangedEventArgs args)
        {
            if (ItemStatusChanged != null)
                ItemStatusChanged(sender, args);
        }

        public event StatusChangedEventHandler ItemStatusChanged;

        public bool Run()
        {
            if (!_specification.Valid)
                throw new Exception("Specification is invalid: " + _specification.Error);

            foreach (var item in _specification.Items)
                item.Run();

            return _specification.Items.All(i => i.Passed);
        }
    }
}